<?php

namespace common\models;

use Yii;
use yii\db\Query;
use backend\models\AuthItem;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $realname
 * @property string $department
 * @property string $post
 * @property string $avatar
 * @property string $is_leader
 * @property string $auth_key
 * @property string $password_hash
 * @property string $confirmation_token
 * @property integer $status
 * @property integer $superadmin
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $registration_ip
 * @property string $bind_to_ip
 * @property string $email
 * @property integer $email_confirmed
 */
class UserModel extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }
    /*关联部门表auth_item*/
    public function getAuthItem(){
        return $this->hasOne(AuthItem::className(),['name'=>'department']);

    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'realname', 'department', 'post', 'auth_key', 'password_hash', 'created_at', 'updated_at'], 'required'],
            [['status', 'superadmin', 'created_at', 'updated_at', 'email_confirmed'], 'integer'],
            [['username', 'realname', 'department', 'post', 'avatar', 'is_leader', 'password_hash', 'confirmation_token', 'bind_to_ip'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['registration_ip'], 'string', 'max' => 15],
            [['email'], 'string', 'max' => 128],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => '用户名',
            'realname' => '名称 ',
            'department' => '部门',
            'post' => '职位',
            'avatar' => 'Avatar',
            'is_leader' => 'Is Leader',
            'auth_key' => 'Auth Key',
            'password_hash' => 'Password Hash',
            'confirmation_token' => 'Confirmation Token',
            'status' => 'Status',
            'superadmin' => 'Superadmin',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'registration_ip' => 'Registration Ip',
            'bind_to_ip' => 'Bind To Ip',
            'email' => '邮箱',
            'email_confirmed' => 'Email Confirmed',
        ];
    }

    /**
     * 取某一用户真实姓名
     *
     * @param $id
     * @return mixed
     */
    public function getRealname($id)
    {
        $users = $this->getUsers();
        return $users[$id];
    }

    /**
     * 由用户表 id为键，realname为值组成的一维数组
     *
     * @return array
     */
    public function getUsers()
    {
        $userArray = (new \yii\db\Query())
            ->select(['id', 'realname'])
            ->from($this->tableName())
            ->all();

        return yii\helpers\ArrayHelper::map($userArray, 'id', 'realname');
    }


    /**
     * 取出部门用户数据列表
     *
     * @param $data  部门条件
     * @return array 多维数组
     */
    public function getDepartmentUsers($data = array())
    {
        //$where = ['type' => '5'];
        $where = array();
        if (!empty($data)) {
            $where = $data;
        }
        $queryBulider = new yii\db\Query();
        $departments = $queryBulider
            ->select('user.*,d.description as department_desc')
            ->from('user')
            ->where($where)
            ->andWhere([ 'status'=> '1'])
            ->leftjoin('auth_item d', 'user.department=d.name')
            ->groupBy('department')
            ->all();

        if (!empty($departments) && is_array($departments)) {
            foreach ($departments as $key => $value) {
                if($value['department_desc']){
                    $departments[$key]['department'] = $value['department_desc'];
                }else{
                    $departments[$key]['department'] = $value['department'];
                }
                $rows = $queryBulider
                    ->select(['id', 'realname', 'username', 'post'])
                    ->from($this->tableName())
                    ->where(['in', 'department', $value['department']])
                    ->andWhere([ 'status'=> '1'])
                    ->groupBy(['id'])
                    ->all();

                if (!empty($rows) && is_array($rows)) {
                    $departments[$key]['users'] = $rows;
                }
            }
        }
      return $departments;
    }

    /**
     * 用户列表
     *
     * @param $data
     * @return array
     */
    public function getList($data = array())
    {
        $queryBulider = new yii\db\Query();
        $queryBulider->select([])
            ->from($this->tableName())
            ->where(['and', 'department!=""'])
            ->andWhere(['like', 'status', '1']);

        if (!empty($data)) {
            //$queryBulider->where(['or', 'department!="总裁办"', 'department!="风控管理中心"', 'department!="财务部"', 'department!="技术部"']);
            $queryBulider->where($data);
        }

        $list = $queryBulider->groupBy(['id'])
            ->all();

        return $list;
    }

    /**
     * 部门人员列表
     * @param array $data
     * @return array
     */
    public function getDepartmentUsersList($data = array())
    {
        $queryBulider = new yii\db\Query();
        $queryBulider->select('user.id,user.username,user.realname,user.department,user.avatar,user.is_leader,ai.description')
            ->from($this->tableName())
            ->leftJoin('auth_item ai','user.department=ai.name');
            //->where(['and', 'department!=""']);
        if (!empty($data)) {
            //$queryBulider->where(['or', 'department!="总裁办"', 'department!="风控管理中心"', 'department!="财务部"', 'department!="技术部"']);
            $queryBulider->where($data);
        }
        $list = $queryBulider->groupBy(['user.id'])
            ->indexBy('id')
            ->all();

        return $list;
    }

    /*
     * 获取用户名字的字符串
     * * * @auth ly
     * retutn string
     * */
    public function getUserStr($access_users)
    {
        $user_string = '';
        if (!empty($access_users)) {//目前初步考虑字段里面的id是由逗号隔开
            $user_id_array = explode(',', $access_users);
            foreach ($user_id_array as $val) {
                $user_name = self::find()->with('authItem')->where("id=:id", [':id' => $val])->one();
                if (!empty($user_name)) {
                    if (!empty($user_string)) {
                        $user_string .= '、';
                    }
                    $user_string .= $user_name['authItem']['description'] . $user_name['realname'];
                }
            }
        }
        return $user_string;
    }
    /*
    * 获取用户名字的字符串
    * * * @auth ly
    * retutn string
    * */
    public function getUserStrNdepartment($access_users)
    {
        $user_string = '';
        if (!empty($access_users)) {//目前初步考虑字段里面的id是由逗号隔开
            $user_id_array = explode(',', $access_users);
            foreach ($user_id_array as $val) {
                $user_name = self::find()->with('authItem')->where("id=:id", [':id' => $val])->one();
                if (!empty($user_name)) {
                    if (!empty($user_string)) {
                        $user_string .= '、';
                    }
                    $user_string .= $user_name['realname'];
                }
            }
        }
        return $user_string;
    }
}